package com.fenyin.samples.study.netty.http;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;

/**
 * Echoes back any received data from a client.
 */
public class HttpServer {

    private final int port;
    private final String filePath;

    public HttpServer(int port,String filePath) {
        this.port = port;
        this.filePath = filePath;
    }

    public void run() {
        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
            	ChannelPipeline pipeline = Channels.pipeline();
            	pipeline.addLast("decoder", new HttpRequestDecoder());
            	pipeline.addLast("encoder", new HttpResponseEncoder());
            	pipeline.addLast("handler", new HttpServerHandler(filePath));
            	return pipeline;
            }
        });

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(port));
    }

    public static void main(String[] args) throws Exception {
        int port = 9998;
        String filePath = "D:\\temp";
        new HttpServer(port,filePath).run();
    }
}
